/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shmallarchitect.jpa.controllers;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
import shmallarchitect.jpa.controllers.exceptions.NonexistentEntityException;
import shmallarchitect.jpa.controllers.exceptions.RollbackFailureException;
import shmallarchitect.jpa.entities.Card;
import shmallarchitect.jpa.entities.Resource;

/**
 *
 * @author jaccus
 */
public class ResourceJpaController {
    @javax.annotation.Resource(mappedName="utx")
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "ShmallArchitectPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(shmallarchitect.jpa.entities.Resource resource) throws RollbackFailureException, Exception {
        if (resource.getCards() == null) {
            resource.setCards(new HashSet<Card>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Set<Card> attachedCards = new HashSet<Card>();
            for (Card cardsCardToAttach : resource.getCards()) {
                cardsCardToAttach = em.getReference(cardsCardToAttach.getClass(), cardsCardToAttach.getId());
                attachedCards.add(cardsCardToAttach);
            }
            resource.setCards(attachedCards);
            em.persist(resource);
            for (Card cardsCard : resource.getCards()) {
                cardsCard.getResources().add(resource);
                cardsCard = em.merge(cardsCard);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(shmallarchitect.jpa.entities.Resource resource) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Resource persistentResource = em.find(Resource.class, resource.getId());
            Set<Card> cardsOld = persistentResource.getCards();
            Set<Card> cardsNew = resource.getCards();
            Set<Card> attachedCardsNew = new HashSet<Card>();
            for (Card cardsNewCardToAttach : cardsNew) {
                cardsNewCardToAttach = em.getReference(cardsNewCardToAttach.getClass(), cardsNewCardToAttach.getId());
                attachedCardsNew.add(cardsNewCardToAttach);
            }
            cardsNew = attachedCardsNew;
            resource.setCards(cardsNew);
            resource = em.merge(resource);
            for (Card cardsOldCard : cardsOld) {
                if (!cardsNew.contains(cardsOldCard)) {
                    cardsOldCard.getResources().remove(resource);
                    cardsOldCard = em.merge(cardsOldCard);
                }
            }
            for (Card cardsNewCard : cardsNew) {
                if (!cardsOld.contains(cardsNewCard)) {
                    cardsNewCard.getResources().add(resource);
                    cardsNewCard = em.merge(cardsNewCard);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = resource.getId();
                if (findResource(id) == null) {
                    throw new NonexistentEntityException("The resource with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Resource resource;
            try {
                resource = em.getReference(Resource.class, id);
                resource.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The resource with id " + id + " no longer exists.", enfe);
            }
            Set<Card> cards = resource.getCards();
            for (Card cardsCard : cards) {
                cardsCard.getResources().remove(resource);
                cardsCard = em.merge(cardsCard);
            }
            em.remove(resource);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<shmallarchitect.jpa.entities.Resource> findResourceEntities() {
        return findResourceEntities(true, -1, -1);
    }

    public List<shmallarchitect.jpa.entities.Resource> findResourceEntities(int maxResults, int firstResult) {
        return findResourceEntities(false, maxResults, firstResult);
    }

    private List<shmallarchitect.jpa.entities.Resource> findResourceEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Resource as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public shmallarchitect.jpa.entities.Resource findResource(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Resource.class, id);
        } finally {
            em.close();
        }
    }

    public int getResourceCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Resource as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
